package com.lmq.Utils


import org.apache.spark.sql.catalyst.expressions.Expression
import org.apache.spark.sql.{Column, DataFrame}
import org.apache.spark.sql.functions.udf


import scala.collection.mutable

object MyUtils {
  /**
   * combine the seqItems with itemId to a new array.
   */
  val combTolist = udf((seqItems:mutable.WrappedArray[String],itemId:String) => {
//    seqItems
          mutable.ArrayBuffer[String]() ++= seqItems += itemId
  })


  /**
   * Transfer an array x with any value in it to a string.
   */
  val toStrFnc = udf((x:mutable.WrappedArray[AnyVal])=>x.mkString(","))


  val combTimeList = udf((enventdate:String, timeframe:String) => {

    timeframe.toLong + timeframe.toLong
  })

  def toSingleCSV(frame:DataFrame, header:Boolean, path:String) = {
    try {
        frame.coalesce(1).write
          .option("header",s"$header")
          .csv(path)
    }
    catch {
      case ex:Exception => {
        println("[ERROR]==========================================")
        println(s"Ignoring exception $ex. Exiting...")
        println("==========================================")

      }
    }

  }

  def trancUseSym(sym:String) = udf((Arr:mutable.WrappedArray[String])=>
  {
    val ints = mutable.ArrayBuffer[Int]()
    for (i <- Arr.indices) {
        if (Arr(i)!="0") ints.append(i)
    }
    ints.mkString(sym)
  })

  val smlLetter: Array[Char] = Array('a','b','c','d','e','f',
    'g','h','i','j','k','l',
    'm','n','o','p','q','r','s','t','u','v',
    'w','x','y','z'
  )
  val CapLetter = Array('A','B','C','D','E','F',
    'G','H','I','J','K','L',
    'M','N','O','P','Q','R','S','T','U','V',
    'W','X','Y','Z'
  )
  val splitName = udf( (sName:String) => {
    var s = ""
   if (sName!=null) {
     val Name = sName.toString
    s = s+Name.head

    for (i <- 1 to Name.length-1) {
//      if (CapLetter.contains(Name(i)) && smlLetter.contains(Name(i-1))) s = s + '|'+ Name(i)
      if (CapLetter.contains(Name(i)) &&  Name(i-1)!=' ') s = s + '|'+ Name(i)
      else s =  s+ Name(i)

    }
     s
  }
    else sName
  }

  )

//  val toPosiFunc = udf((
//  _c5:String,
//  _c6:String,
//  _c7:String,
//  _c8:String,
//  _c9:String,
//  _c10: String,
//  _c11: String,
//  _c12: String,
//  _c13: String,
//  _c14: String,
//  _c15: String,
//  _c16: String,
//  _c17: String,
//  _c18: String,
//  _c19: String,
//  _c20: String,
//  _c21: String,
//  _c22: String,
//  _c23: String
//  )=>{
//    _c23
//
//  })



}
